package reflect;
import java.lang.reflect.Constructor;
/**
 * 使用指定的构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws Exception {
        Person p = new Person("张三");
        System.out.println(p);

        Class cls = Class.forName("reflect.Person");
        /*
          Constructor是反射对象之一，表示构造器对象
         */
        //获取无参构造器
        //Object obj1 = cls.newInstance();   //new Person();
        Constructor con1 = cls.getConstructor();
        Object obj1 = con1.newInstance();   //new Person();
        System.out.println(obj1);   //Person{name='null', age=0}
        //获取String参构造器
        Constructor con2 = cls.getConstructor(String.class);
        Object obj2 = con2.newInstance("李四");   //new Person("李四");
        System.out.println(obj2);   //Person{name='李四', age=0}
        //获取String+int参构造器
        Constructor con3 = cls.getConstructor(String.class, int.class);
        Object obj3 = con3.newInstance("王五", 20);   //new Person("王五", 20);
        System.out.println(obj3);   //Person{name='王五', age=20}
    }
}
